﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using StoreDemo.Domain.Data;
using StoreDemo.Domain.Entities;

namespace StoreDemo.Domain.Services
{
    internal class ProductService : IProductService
    {
        private readonly IUnitOfWorkFactory _unitOfWorkFactory;

        public ProductService(IUnitOfWorkFactory unitOfWorkFactory)
        {
            _unitOfWorkFactory = unitOfWorkFactory;
        }

        #region Implementation of IProductService

        IEnumerable<Product> IProductService.GetAllProducts()
        {
            IRepository<Product> productRepository = _unitOfWorkFactory.GetUnitOfWork().GetRepository<Product>();
            IList<Product> allProducts = productRepository.All.ToList();
            return new ReadOnlyCollection<Product>(allProducts);
        }

        public Product Get(int byProductId)
        {
            IRepository<Product> productRepository = _unitOfWorkFactory.GetUnitOfWork().GetRepository<Product>();
            Product product = productRepository.All.Single(x => x.ProductId == byProductId);
            return product;
        }

        void IProductService.Save(Product product)
        {
            IUnitOfWork unitOfWork = _unitOfWorkFactory.GetUnitOfWork();
            IRepository<Product> productRepository = unitOfWork.GetRepository<Product>();
            product.Created = DateTime.Now;
            productRepository.Insert(product);
            unitOfWork.Save();
        }

        public void Update(Product product)
        {
            IUnitOfWork unitOfWork = _unitOfWorkFactory.GetUnitOfWork();
            IRepository<Product> productRepostiory = unitOfWork.GetRepository<Product>();
            productRepostiory.Update(product);
            unitOfWork.Save();
        }

        public void Delete(int byProductId)
        {
            IUnitOfWork unitOfWork = _unitOfWorkFactory.GetUnitOfWork();
            IRepository<Product> productRepostiory = unitOfWork.GetRepository<Product>();
            productRepostiory.Delete(byProductId);
            unitOfWork.Save();
        }

        #endregion
    }
}